<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\CourseTypeModel;
use Illuminate\Http\Request;

class CourseTypeController extends Controller
{
    public function list(Request $request)
    {
        $data = CourseTypeModel::where('company_id', $request->company_id)->orderBy('id', 'desc')->get();
        return self::sendOk($data);
    }
    public function edit(Request $request)
    {
        $courseType = CourseTypeModel::where('id', $request->id)->first();
        if (!$courseType) {
            return self::sendError('Course type not found');
        }
        if ($courseType->company_id != $request->company_id) {
            return self::sendError('You are not authorized to edit this course type');
        }
        
        $courseType->update($request->only('name', 'desc'));
        return self::sendOk($courseType);
    }
    public function add(Request $request)
    {
        $name = $request->input('name');
        $companyId = $request->input('company_id');
        $courseType = CourseTypeModel::where('company_id', $companyId)->where('name', $name)->first();
        if ($courseType) {
            return self::sendError('Course type already exists');
        }
        $courseType = CourseTypeModel::create([
            'name' => $name,
            'company_id' => $companyId,
            'desc' => $request->input('desc'),
        ]);
        return self::sendOk($courseType);
    }
    public function delete(Request $request)
    {
        $id = request()->input('id');
        $courseType = CourseTypeModel::where('id', $id)->first();
        if($courseType->company_id != $request->company_id){
            return self::sendError('You are not authorized to delete this course type');
        }
        $courseType->delete();
        return self::sendOk();
    }
}
